﻿using SKeeper.Application.Services;
using SKeeper.Application.Services.Invoice;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using SKeeper.Application.ViewModels.Invoice;
using SKeeper.Persistence.Facade;

namespace SKeeper.Controllers
{
    [Authorize]
    public class InvoiceController : Controller
    {
        private IInvoiceControllerService service;
        private DomainModelFacade context;

        public InvoiceController()
        {
            this.context = new DomainModelFacade();
            this.service = new InvoiceControllerService(this.context);
        }

        public ActionResult Index()
        {
            var userId = this.User.Identity.GetUserId();
            var viewModel = this.service.GetIndexViewModel(userId);
            return View(viewModel);
        }

        public ActionResult Warehouse(int id)
        {
            var model = this.service.GetWarehouseInvoices(id);

            return this.View(model);
        }

        /// <summary>
        /// Creates new Invoice
        /// </summary>
        /// <param name="id">warehouseId</param>
        /// <returns></returns>
        public ActionResult Add(int id)
        {
            this.ViewBag.Error = this.TempData["Error"];
            InvoiceViewModel model = this.service.InvoiceAddViewModel(id);

            return this.View(model);
        }

        [HttpPost]

        public ActionResult Add(InvoiceViewModel model)
        {
            using (var t = this.context.Database.BeginTransaction())
            {
                try
                {
                    this.service.CreateInvoice(model);
                    t.Commit();
                }
                catch(Exception ex)
                {
                    this.TempData["Error"] = ex.Message;
                    t.Rollback();
                }

            }
            return this.RedirectToAction("Warehouse", new { id = model.WarehouseId });
        }

        public ActionResult Preview(int id)
        {
            var model = this.service.GetInvoiceViewModel(id);
            return this.View(model);
        }
    }
}